<template>
  <div style="width: 100%;" class="commonEntityDialog">
    <el-dialog :close-on-click-modal="false"
               :append-to-body="true"
               width="1000px"
               :visible.sync="visible"
               :destroy-on-close="true">
      <template slot="title">
        <div class="dialogTitle">
          <span>新建实体</span>
          <el-tabs v-model="activeName">
            <el-tab-pane label="基本信息" name="1" disabled></el-tab-pane>
            <el-tab-pane label="接口" name="2" disabled></el-tab-pane>
            <el-tab-pane label="属性" name="3" disabled></el-tab-pane>
            <el-tab-pane label="功能配置" name="4" disabled></el-tab-pane>
            <el-tab-pane v-if="showComponent" label="关系" name="5" disabled></el-tab-pane>
          </el-tabs>
          <span></span>
        </div>
      </template>
      <div style="width: 100%;height: 500px;overflow-y: scroll" v-if="visible">
        <base-info :show="activeName==='1'" ref="step1"></base-info>
        <interface :show="activeName==='2'" ref="step2"></interface>
        <properties :show="activeName==='3'" ref="step3"></properties>
        <function :show="activeName==='4'" ref="step4"></function>
        <relation :show="activeName==='5'" ref="step5"></relation>
      </div>

      <div slot="footer" style="text-align: center">
        <el-button size="medium" v-if="activeName==='1'" type="primary" @click="saveBaseInfo">保存</el-button>
        <el-button size="medium" v-if="activeName!=='1'" @click="changeStep(-1)">上一步</el-button>
        <el-button size="medium" :disabled="!saveFirst"
                   v-if="showComponent?activeName!=='5':activeName!=='4'"
                   @click="changeStep(+1)">下一步
        </el-button>
        <el-button size="medium"
                   v-if="showComponent?activeName==='5':activeName==='4'"
                   type="primary"
                   @click="saveAll">
          保存
        </el-button>
        <el-button size="medium" @click="visible=false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import BaseInfo from "@/views/DMDComponent/entityTemp/baseInfo.vue";
import Interface from "@/views/DMDComponent/entityTemp/Interface.vue";
import Properties from "@/views/DMDComponent/entityTemp/Properties.vue";
import Relation from "@/views/DMDComponent/entityTemp/Relation.vue";
import Function from "@/views/DMDComponent/entityTemp/Function.vue";

import * as entity from "@/api/modulManage/entity"
import * as relation from "@/api/modulManage/relation"

export default {
  name: "commonEntityDialog",
  components: {Function, Relation, Properties, Interface, BaseInfo},
  inject: ["temp"],
  provide() {
    return {
      allFormData: () => this.allFormData,
      dialogType: () => this.dialogType,
    }
  },
  data() {
    return {
      visible: false,
      activeName: "",
      activeIndex: 0,

      EMTabs: ["1", "2", "3", "4", "5"],
      ERTabs: ["1", "2", "3", "4"],

      saveFirst: false,

      dialogType: "add",

      allFormData: {
        toOid: "",
        fromOid: "",
        implTypeInterfaces: [],
        functionInterfaces: [],
        functionTypeInterfaces: [],
        typeAttributes: [],
      },

      api: {entity, relation}
    }
  },
  computed: {
    /**
     * 为关系实体（true）
     * */
    showComponent() {
      return this.temp === "EM";
    }
  },
  methods: {
    /**
     * 保存所有数据
     * */
    saveAll() {
      let api = this.showComponent ? "entity" : "relation";
      if (!this.showComponent) {
        let {form} = this.$refs['step4'].getTabData();
        this.getStep4Data(form);
      }

      this.api[api].update(this.allFormData).then(() => {
        this.visible = false;
        this.$message.success("保存成功");
        this.$emit("refresh");
      })
    },
    /**
     * 保存基本信息
     * 保存了基本信息才可以下一步
     * */
    async saveBaseInfo() {
      let method = this.dialogType === "add" ? "add" : "update";
      let api = this.showComponent ? "entity" : "relation";

      let {form, flag} = await this.$refs["step1"].getTabData();
      Object.assign(this.allFormData, form);

      let data = form.functionInterfaces;
      let functionTypeInterfaces = []

      data.forEach(item => {
        if (item.extendsFlag !== 1) {
          functionTypeInterfaces.push({interfaceId: item.oid, settingsJson: ""})
        }
      })
      if (!this.showComponent) {
        form.fromOid = "," + form.fromOid.join(",") + ",";
        form.toOid = "," + form.toOid.join(",") + ",";
      }
      if (flag) {
        this.api[api][method]({...form, functionTypeInterfaces}).then(_ => {
          this.saveFirst = true;
          this.$message.success("保存成功");
        })
      }
    },

    /**
     * @param v -1 上一步  +1 下一步
     * 关系实体（EM）和实体模型（ER）公用
     * */
    async changeStep(v) {
      let tabs = this.EMTabs;
      if (!this.showComponent) {
        tabs = this.ERTabs;
      }

      if (v > 0) {
        let {form} = await this.$refs['step' + this.activeName].getTabData();

        switch (this.activeName) {
          case "1":
            Object.assign(this.allFormData, form);
            Object.assign(this.allFormData, {step1: this.deepCopy(form), saveFirst: true});
            break;
          case "2":
            let implTypeInterfaces = [];
            if (!form && form.length === 0) {
              break;
            }
            form.forEach(item => {
              implTypeInterfaces.push({"interfaceId": item.oid});
            })
            Object.assign(this.allFormData, {implTypeInterfaces: implTypeInterfaces});
            Object.assign(this.allFormData, {step2: this.deepCopy(form), saveStep2: true});
            break;
          case "3":
            let typeAttributes = [];
            if (!form && form.length === 0) {
              break;
            }
            form.forEach(item => {
              typeAttributes.push({"attributeId": item.oid});
            })
            Object.assign(this.allFormData, {typeAttributes: typeAttributes})
            Object.assign(this.allFormData, {step3: this.deepCopy(form)})
            break;
          case "4":
            this.getStep4Data(form);
            break;
        }
      }
      this.activeName = tabs[this.activeIndex += v];
    },
    getStep4Data(form) {
      let functionInterfaces = [];
      if (form && form.length !== 0) {
        form.forEach(item => {
          let obj = this.deepCopy(item);
          delete obj.interfaceId;
          functionInterfaces.push({interfaceId: item.interfaceId, settingsJson: JSON.stringify(obj)})
        })

        let ids = functionInterfaces.map(item => item.interfaceId);

        this.allFormData.functionInterfaces.forEach(item => {
          let index = ids.indexOf(item.oid);
          if (index === -1 && item.oid) {
            functionInterfaces.push({interfaceId: item.oid, settingsJson: ""})
          }
        })

        this.$set(this.allFormData, "functionTypeInterfaces", functionInterfaces);
        this.$set(this.allFormData, "step4", {step1: this.deepCopy(form), saveStep4: true});
      }
    },
    /**
     * @param row 查看 行内数据（row）
     * */
    view(row) {
      this.dialogType = "view";
      let api = this.showComponent ? "entity" : "relation";
      this.api[api].getDetail({oid: row.oid}).then(res => {
        this.visible = true;
        this.saveFirst = true;
        this.activeName = "1";
        this.activeIndex = 0;
        this.$nextTick(() => {
          this.$refs['step1'].view_edit("view", res.data.data)
          Object.assign(this.allFormData, res.data.data);
        })
      })
    },
    /**
     * @param row 编辑 行内数据（row）
     * */
    edit(row) {
      this.dialogType = "edit";
      let api = this.showComponent ? "entity" : "relation";
      this.api[api].getDetail({oid: row.oid}).then(res => {
        this.visible = true;
        this.saveFirst = true;
        this.activeName = "1";
        this.activeIndex = 0;
        this.$nextTick(() => {
          this.$refs['step1'].view_edit("edit", res.data.data)
          Object.assign(this.allFormData, res.data.data);
        })
      })
    },
    open() {
      this.visible = true;
      this.activeName = "1";
      this.activeIndex = 0;
      this.dialogType = "add";
      this.saveFirst = false;
    },
    close() {
      this.visible = false;
      this.allFormData = {};
    },
  },
  mounted() {
  },
  created() {
  },
  watch: {}
}
</script>

<style lang="scss">

.dialogTitle {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  flex-wrap: nowrap;

  > span {
    display: flex;
    flex-direction: column;
    justify-content: center;
  }

  .el-tabs {
    .el-tabs__header {
      margin: 0;

      .el-tabs__nav-wrap::after {
        height: 0;
      }

      .el-tabs__nav-wrap {
        .el-tabs__nav-scroll {
          .el-tabs__nav {
            .is-disabled {
              color: #303133;
            }

            .is-active {
              color: #409EFF !important;
            }
          }
        }
      }
    }
  }
}
</style>
